package com.example.unique.ui.chat
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.lifecycle.Observer
import com.example.unique.database.DatabaseHelper
import com.example.unique.databinding.ChatBinding


class ChatFragment:Fragment() {

    private var _binding:ChatBinding?=null
    private val binding get()=_binding!!
    private lateinit var chatViewModel: ChatViewModel
    private lateinit var club:String
    private lateinit var userDatabase: DatabaseHelper
    private lateinit var memberAdapter: MemberAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        club = activity?.intent?.getStringExtra("club").toString()
        // 初始化数据库实例
        userDatabase=DatabaseHelper(requireContext())
        chatViewModel=ChatViewModel(userDatabase)
        chatViewModel.getUserByClub(club)
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding=ChatBinding.inflate(inflater, container, false)
        memberAdapter = MemberAdapter()
        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerView.adapter = memberAdapter
        binding.search.setOnQueryTextListener(object : SearchView.OnQueryTextListener,
            android.widget.SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                query?.let { searchMembersByName(it) }
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                newText?.let { searchMembersByName(it) }
                return true
            }
        })
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        chatViewModel.membersData.observe(viewLifecycleOwner, Observer { members ->
            memberAdapter.submitList(members)
        })

    }
    private fun searchMembersByName(query: String) {
        val members = chatViewModel.membersData.value ?: emptyList()
        val found = members.any { it.name.contains(query, ignoreCase = true) }

        if (found) {
            Toast.makeText(requireContext(), "已找到", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(requireContext(), "未找到匹配的内容", Toast.LENGTH_SHORT).show()
        }
    }
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null // 清理绑定的视图
    }

}
